package com.small.nacos.naming.consistency;

import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author zhoujin
 * @Date 2022/10/29 12:33
 */
@Service("consistencyDelegate")
public class DelegateConsistencyServiceImpl implements ConsistencyService{

    @Resource(name = "distroConsistencyService")
    private ConsistencyService ephemeralConsistencyService;

    @Override
    public void put(String key, Object value) throws NacosException {
        mapConsistencyService(key).put(key, value);
    }

    @Override
    public void remove(String key) throws NacosException {
        mapConsistencyService(key).remove(key);
    }

    @Override
    public Datum get(String key) throws NacosException {
        return mapConsistencyService(key).get(key);
    }

    @Override
    public void listen(String key, RecordListener listener) throws NacosException {
        mapConsistencyService(key).listen(key, listener);
    }

    @Override
    public void unListen(String key, RecordListener listener) throws NacosException {
        mapConsistencyService(key).unListen(key, listener);
    }

    private ConsistencyService mapConsistencyService(String key) {
        return KeyBuilder.matchEphemeralKey(key) ? ephemeralConsistencyService : null;
    }
}
